//
//  HtmlController.swift
//  soapp
//
//  Created by zhuxietong on 2016/11/10.
//  Copyright © 2016年 zhuxietong. All rights reserved.
//

import UIKit
import WebKit
import JoLoading
import Eelay



public var new_js_config:WebConfiguration{
    
    let cf = WebConfiguration()
    cf.initBlock = { hander,controller in
        controller.add(hander, name: "__sendtoapp")
        let appUserInfo =
            "function __getClientInfo(){" +
                "    return {'device-type':'iOS'} ;" +
        "}"
        let script11 = WKUserScript(source: appUserInfo, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: true)
        let script12 = WKUserScript(source: appUserInfo, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
        controller.addUserScript(script11)
        controller.addUserScript(script12)
    }
    
    //    js.hander_block = {
    //        controller,message in
    //        if let one = message.body as? Dictionary<String, AnyObject>
    //        {
    //            let dict = one.mutable_dictionary
    //
    //        }
    //
    //    }
    
    return cf
}



public protocol HTMLControllerDelegate:WKUIDelegate,WKNavigationDelegate {
    var webView:WKWebView?{get set}
    var configuration: WKWebViewConfiguration{get set}
    func initWebview()
    func layWebView(webview:WKWebView)
    
}


extension HTMLControllerDelegate where Self: HTMLController
{
    
    public func initWebview()
    {
        self.webView = WKWebView(frame: [0,0,Swidth,Sheight], configuration: self.configuration)
        
        webView?.sizeToFit()
        webView?.allowsBackForwardNavigationGestures = true
        webView?.uiDelegate = self
        webView?.navigationDelegate = self
        self.layWebView(webview: webView!)
        
    }
    
}




open class HTMLController:TypeInitController {
    
    
    public var htmlRender:HTMLPageRender = BaseHTMLPage.default
    
    public var configuration: WKWebViewConfiguration
    
    public var webView:WKWebView?
    
    
    
    public var contentScan:(String,NSMutableDictionary) ->String = {origin,_ in return origin}
    
    
    open func layWebView(webview: WKWebView) {
        self.jo_contentView.addSubview(webview)
        self.jo_contentView.eelay = [
            [webview,[ee.T.L.B.R]]
        ]
    }
    
    
    
    
    
    required public init(render:HTMLPageRender?=BaseHTMLPage.default,wk_config:WKWebViewConfiguration=WKWebViewConfiguration()) {
        if let rd = render
        {
            self.htmlRender = rd
        }
        self.configuration = wk_config
        super.init()
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    required public init() {
        self.configuration = WKWebViewConfiguration()
        super.init()
    }
    
    
    
    open override func viewDidLoad() {
        self.initWebview()
        super.viewDidLoad()
        
        self.view.backgroundColor = ._background
        self.jo_contentView.backgroundColor = ._background
        //        webView.load(render: htmlRender)
    }
    
    open override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}


extension HTMLController:HTMLControllerDelegate
{
    public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let url = navigationAction.request.url
        let scheme = url?.scheme
        guard let schemeStr = scheme else { return  }
        if schemeStr == "tel" {
            if let u = url
            {
                UIApplication.shared.openURL(u)
            }
        }
        decisionHandler(.allow)
    }
    
    
    public func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        
        JoAlertView(info: "提示".loc,message).append(title: "确定".loc, action: {
            completionHandler()
        }).alert.show(at: self)
    }
    
    public func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        JoAlertView(info: "提示".loc,message).alert.append(title: "取消".loc, action: {
            print("canle")
            completionHandler(false)
        }).append(title: "确定".loc, action: {
            print("confirm")
            completionHandler(true)
        }).show(at: self)
    }
    
    public func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        
    }
    
}

